import time
from machine import Pin, I2C, PWM
from max30102 import MAX30102

# 硬件配置
# --------------------------------------------------
# I2C 引脚 (ESP32-S3 默认 I2C0)
I2C_SDA = Pin(8)
I2C_SCL = Pin(9)
BUZZER_PIN = 13  # 无源蜂鸣器引脚

# 传感器参数
SAMPLING_RATE = 100  # 采样率 (Hz)
LED_CURRENT = 0x1F    # LED电流 (0x00-0xFF)
BEAT_TIMEOUT = 5      # 心跳超时阈值 (秒)

# 初始化硬件
# --------------------------------------------------
i2c = I2C(0, sda=I2C_SDA, scl=I2C_SCL, freq=400000)
sensor = MAX30102(i2c=i2c)
buzzer = PWM(Pin(BUZZER_PIN, Pin.OUT))
buzzer.duty(0)  # 初始关闭

# 配置传感器
sensor.set_sample_rate(SAMPLING_RATE)
sensor.set_led_current(red_current=LED_CURRENT, ir_current=0)  # 禁用IR LED

# 心跳检测参数
last_beat_time = time.time()
red_buffer = []
threshold = 20000  # 根据实际信号调整

def trigger_alarm():
    """触发蜂鸣器报警 (1kHz频率)"""
    buzzer.freq(1000)
    buzzer.duty(512)  # 50%占空比
    time.sleep(0.5)
    buzzer.duty(0)

def detect_heartbeat(samples):
    """简易心跳检测算法"""
    global last_beat_time
    beat_detected = False
    
    # 计算信号变化率
    diffs = [samples[i] - samples[i-1] for i in range(1, len(samples))]
    positive_crossings = sum(1 for d in diffs if d > threshold)
    
    if positive_crossings > 2:  # 检测到有效心跳
        last_beat_time = time.time()
        beat_detected = True
    
    return beat_detected

try:
    print("开始心跳监测...")
    while True:
        # 读取传感器数据
        sensor.refresh()
        red = sensor.pop_red_from_storage()
        
        if red is not None:
            red_buffer.extend(red)
            
            # 保持缓冲区长度
            if len(red_buffer) > 100:
                red_buffer = red_buffer[-100:]
                
            # 执行心跳检测
            if len(red_buffer) >= 100:
                if detect_heartbeat(red_buffer[-100:]):
                    print("❤ 心跳检测正常")
        
        # 超时检测
        if time.time() - last_beat_time > BEAT_TIMEOUT:
            print("⚠️ 未检测到心跳！")
            trigger_alarm()
        
        time.sleep(0.1)

except KeyboardInterrupt:
    buzzer.duty(0)
    sensor.shutdown()
    print("系统安全关闭")